package com.jinkeen.xiaxie.customView

import android.content.Context
import android.inputmethodservice.Keyboard
import android.inputmethodservice.KeyboardView
import android.util.AttributeSet
import android.widget.EditText
import com.jinkeen.xiaxie.R

/**
 * @description: TODO
 * @author whz
 * @date 2022-07-12 15:14
 * @version 1.0
 **实现自定义键盘思路:**
1. 在res包下创建xml目录,Keyboard标签来定义键盘布局
2. 创建IKeyboardView类并继承KeyboardView类,设置键盘布局（数字和字母）
3. 处理自定义键盘按键的点击事件以及预览，并实现数字和字母键盘(包括大小写)之间的切换
4. 绑定EditText，并且屏蔽系统键盘（实现点击切换绑定多个EditText）
5. 使用
 */

class MyKeyBoard : KeyboardView {

    private var arrays = arrayOf(
        Keyboard.KEYCODE_SHIFT, Keyboard.KEYCODE_MODE_CHANGE,
        Keyboard.KEYCODE_CANCEL, Keyboard.KEYCODE_DONE, Keyboard.KEYCODE_DELETE,
        Keyboard.KEYCODE_ALT
    )


    /**
     * 数字键盘
     */
    private var numKeyboard: Keyboard? = null

    /**
     * 字母键盘
     */
    private var letterKeyboard: Keyboard? = null

    /**
     * 绑定的输入框
     */
    private var mEditText: EditText? = null

    /**
     * 是否发生键盘切换
     */
    private var changeLetter: Boolean = true

    /**
     *是否为大小
     */
    private var isCapital = false

    private var noLists = ArrayList<Int>()


    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        numKeyboard = Keyboard(context, R.xml.keyboard_num)
        letterKeyboard = Keyboard(context, R.xml.keyboard_letter)
        //设置一些不需要预览的键位
        for (i in arrays.indices) {
            noLists.add(arrays[i])
        }
        //默认使用数字键盘
        keyboard = numKeyboard
        //是否启用预览
        isPreviewEnabled = true
        //键盘动作监听
        onKeyboardActionListener = object : KeyboardView.OnKeyboardActionListener {
            override fun onPress(primaryCode: Int) {
                canShowPreview(primaryCode)
            }

            override fun onRelease(primaryCode: Int) {

            }

            override fun onKey(primaryCode: Int, keyCodes: IntArray?) {
                val editable = mEditText?.text
                val start = mEditText?.selectionStart
                when (primaryCode) {
                    Keyboard.KEYCODE_DELETE -> {
                        if (editable != null && editable.isNotEmpty() && start!! > 0) {
                            editable.delete(start - 1, start)
                        }
                    }
                    Keyboard.KEYCODE_MODE_CHANGE -> {
                        //字母键盘与数字键盘切换
                        changeKeyboard(!changeLetter)
                    }
                    Keyboard.KEYCODE_DONE -> {
                        //完成
                        changeKeyboard(!changeLetter)
                    }
                    Keyboard.KEYCODE_SHIFT -> {
                        //大小写切换
                        changeCapital(!isCapital)
                        keyboard = letterKeyboard
                    }
                    else -> {
                        editable?.insert(start!!, primaryCode.toChar().toString())
                    }
                }
            }

            override fun onText(text: CharSequence?) {

            }

            override fun swipeLeft() {

            }

            override fun swipeRight() {

            }

            override fun swipeDown() {

            }

            override fun swipeUp() {

            }

        }

    }

    fun setEditText(editText: EditText) {
        this.mEditText = editText
    }

    /**
     * 判断是否需要预览key
     */
    private fun canShowPreview(primaryCode: Int) {
        isPreviewEnabled = !noLists.contains(primaryCode)
    }

    /**
     * 切换键盘类型
     */
    private fun changeKeyboard(b: Boolean) {
        changeLetter = b
        keyboard = if (b) {
            letterKeyboard
        } else {
            numKeyboard
        }
    }

    /**
     * 切换键盘大小写
     */
    private fun changeCapital(b: Boolean) {
        isCapital = b
        val lists = letterKeyboard?.keys
        for (i in lists?.indices!!) {
            if (lists[i].label != null && isKey(lists[i].label.toString())) {
                if (isCapital) {
                    lists[i].label = lists[i].label.toString().toUpperCase()
                    lists[i].codes[0] = lists[i].codes[0] - 32
                } else {
                    lists[i].label = lists[i].label.toString().toLowerCase()
                }
            } else if (lists[i].label != null && lists[i].label.toString() == "小写") {
                lists[i].label = "大写"
            } else if (lists[i].label != null && lists[i].label.toString() == "大写") {
                lists[i].label = "小写"
            }
        }
    }

    /**
     * 判读此key是否正确,且存在**
     */
    private fun isKey(key: String): Boolean {
        val lowercase = "abcdefghijklmnopqrstuvwxyz"
        return lowercase.indexOf(key.toLowerCase()) > -1
    }

}